using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using MVCCornucopia.Data;
using MVCCornucopia.Data.Enums;

namespace MVCCornucopia.Models
{ 
    public class EmployeeRepository : IRepository
    {
        CornucopiaDatabaseEntities context = new CornucopiaDatabaseEntities();

        public IQueryable<IDataItem> All
        {
            get { return context.Employees; }
        }


        public IDataItem Find(int id)
        {
            return context.Employees.FirstOrDefault(e => e.EmployeeId == id);
        }

        public IDataItem Create()
        {
            var emp = context.Employees.CreateObject();

            //-- note nice use of enums.. enums are auto-generated from DB via TTT.
            //   couple examples of avoiding underpost/overpost
            //   by isolating Employee from the create/edit via use of ViewModel
            emp.InternalControlNumber = Guid.NewGuid();
            emp.EmployeeSalaryLevelId = (int)SalaryLevel.Level1;

            return emp;
        }

        public void InsertOrUpdate(IDataItem dataItem)
        {
            var employee = dataItem as Employee;
            if (employee.EmployeeId == default(int)) {
                // New entity
                context.Employees.AddObject(employee);
            } else {
                // attach it if it isn't already attached
                if (context.ObjectStateManager.GetObjectStateEntry(employee).State == EntityState.Detached)
                {
                    context.Employees.Attach(employee);
                    context.ObjectStateManager.ChangeObjectState(employee, System.Data.EntityState.Modified);
                }
            }
        }

        public void Delete(int id)
        {
            var employee = (Employee)Find(id);
            context.Employees.DeleteObject(employee);
        }

        public void Save()
        {
            context.SaveChanges();
        }
    }

}